﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Web;
using System.Security.Principal;

namespace Cm.Web.Common
{
    public static class FormsAuthenticationWithRole
    {
        /// <summary>
        /// 设置包含角色信息的票据
        /// </summary>
        /// <param name="name"></param>
        /// <param name="roles">角色信息（以 “,” 作为分隔符）</param>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public static void SetTicketWithRole(string name, string roles)
        {
            HttpContext ctx = HttpContext.Current;
            int ver = 1;
            DateTime issueDate = DateTime.Now;
            DateTime expiration = DateTime.Now.AddDays(7);
            bool isPersistent = false;
            string userData = roles;
            FormsAuthenticationTicket ft = new FormsAuthenticationTicket(ver, name, issueDate, expiration, isPersistent, userData);
            string hashTicket = FormsAuthentication.Encrypt(ft); //加密序列化验证票为字符串
            HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
            ctx.Response.AppendCookie(userCookie);
        }
        /// <summary>
        /// 初始化当前的上下文（附加角色信息）
        /// 目前授权信息获取是直接从Cookie里取，这样可能带来的问题，权限应用不及时（取决于系统对权限要求的等级）
        /// </summary>
        /// <param name="ctx"></param>
        public static void InitializeFormsAuthenticationInfo()
        {
            HttpContext ctx = HttpContext.Current;
            FormsIdentity Id = (FormsIdentity)ctx.User.Identity;
            FormsAuthenticationTicket Ticket = Id.Ticket; //取得身份验证票
            string[] roles = Ticket.UserData.Split(','); //将身份验证票中的role数据转成字符串数组
            ctx.User = new GenericPrincipal(Id, roles); //将原有的Identity加上角色信息新建一个GenericPrincipal表示当前用户,这样当前用户就拥有了role信息
        }
    }
}
